package com.everydayflash.flar.sample.pv3d {
	import com.everydayflash.flar.sample.pv3d.ARAppBase;
	
	import org.libspark.flartoolkit.core.transmat.FLARTransMatResult;
	import org.libspark.flartoolkit.pv3d.FLARBaseNode;
	import org.libspark.flartoolkit.pv3d.FLARCamera3D;
	import org.papervision3d.objects.DisplayObject3D;
	import org.papervision3d.render.LazyRenderEngine;
	import org.papervision3d.scenes.Scene3D;
	import org.papervision3d.view.Viewport3D;
	
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.utils.ByteArray;		

	[SWF(width=640,height=480,frameRate=60,backgroundColor=0x0)]

	public class PV3DARApp extends ARAppBase {

		protected var _base:Sprite;
		protected var _viewport:Viewport3D;
		protected var _camera3d:FLARCamera3D;
		protected var _scene:Scene3D;
		protected var _renderer:LazyRenderEngine;
		protected var _baseNode:FLARBaseNode;
		
		protected var _resultMat:FLARTransMatResult = new FLARTransMatResult();
		
		
		public function PV3DARApp() {
		}
		
		override protected function init(cameraFile:ByteArray, codeFile:ByteArray, canvasWidth:int, canvasHeight:int, codeWidth:int=80):void {
			super.init(cameraFile, codeFile, canvasWidth, canvasHeight, codeWidth);

			_base = new Sprite();
			addChild(_base);

			_base.addChild(_video);
			//_video.scaleX = _video.scaleY = 2;
			
			_viewport = _base.addChild(new Viewport3D(canvasWidth, canvasHeight, false, true)) as Viewport3D;
			//_viewport.scaleX = _viewport.scaleY = 2;
			_viewport.x = -4; // Magic fix?
			
			_camera3d = new FLARCamera3D(_param);
			
			_scene = new Scene3D();
			_baseNode = _scene.addChild(new FLARBaseNode()) as FLARBaseNode;

			_renderer = new LazyRenderEngine(_scene, _camera3d, _viewport);
			addEventListener(Event.ENTER_FRAME, render);
		}
		
		protected function render(e:Event = null):void {
			_capture.bitmapData.draw(_video);
			if (_detector.detectMarkerLite(_raster, 80) && _detector.getConfidence() > 0.2) {
				_detector.getTransformMatrix(_resultMat);
				_baseNode.setTransformMatrix(_resultMat);
				_baseNode.visible = true;
			} else {
				_baseNode.visible = false;
			}
			_renderer.render();
		}
	}
}